import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';
import moment from 'moment'
import AndroidModule from 'src/utils/AndroidConnent'
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Constant from '../../utils/Constant'//全局变量
import Header from "../../components/header";
import DatePickerPart from '../../components/Tool/DatePickerPart'
import NoData from "../../utils/NoData";


const screenW = Dimensions.get('window').width;
const isIos = Platform.OS == 'ios';

let pageSize = 20
let pageNo = 1;
let itemNo = 0;

export default class WalletHistoryPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            showDatePicker: false,
            showFilterType: false,
            consumeDate: '',
            selectFilterType: '',
            selectFilterTypeTitle: '全部类型',
            recordsList: [],
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            //余额充值、车辆维保、出险记录、检测费、余额提现、合同费用
            
            showTypes: [
                { enumType: 'TradeType', code: '', desc: '全部' },
                { enumType: 'TradeType', code: 1, desc: '车辆维保' },
                { enumType: 'TradeType', code: 5, desc: '出险记录' },
                { enumType: 'TradeType', code: 6, desc: '余额充值' },
                { enumType: 'TradeType', code: 7, desc: '余额提现' },
                { enumType: 'TradeType', code: 8, desc: '余额扣款' },
                { enumType: 'TradeType', code: 12, desc: '订单退款' },
                { enumType: 'TradeType', code: 14, desc: '合同订单' },
                { enumType: 'TradeType', code: 15, desc: '检测订单' },
                { enumType: 'TradeType', code: 22, desc: '车辆订单' },
                
            ]
        }
    }

    componentWillMount() {

    }

    componentWillUnmount() {

    }

    componentDidMount() {
        // this.getTradeTypeList()
        this.getWalletRecordsInfo(true)
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>

                {this.renderTop()}
                {this.renderFilter()}

                <View style={styles.container}>
                    {this.renderList()}

                    {this.renderFilterView()}
                </View>

                <DatePickerPart defaultDate={this.state.consumeDate} show={this.state.showDatePicker} changeState={
                    (val) => { // 时间选择组件显示与否
                        this.setState({
                            showDatePicker: val
                        })
                    }
                } changeDate={(date) => {
                    this.setState({
                        consumeDate: date
                    }, function () {
                        this.getWalletRecordsInfo(true);
                    })

                }} />

            </View>
        );
    }

    renderTop() {
        return (
            <Header navigation={navigation} Title={'费用明细'} hideSepLine={true} />
        )
    }

    renderFilter() {
        return (
            <View style={styles.filterContain}>

                <TouchableOpacity
                    activeOpacity={0.8}
                    style={styles.filterItemContain}
                    onPress={() => {
                        this.setState({
                            showDatePicker: true,
                            showFilterType: false
                        })
                    }}
                >
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={styles.filterText}>{this.state.consumeDate ? this.state.consumeDate : '全部时间'}</Text>
                        <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity
                    activeOpacity={0.8}
                    style={styles.filterItemContain}
                    onPress={() => {
                        let showFilterType = this.state.showFilterType
                        this.setState({
                            showDatePicker: false,
                            showFilterType: !showFilterType
                        })
                    }}
                >
                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={styles.filterText}>{this.state.selectFilterTypeTitle}</Text>
                        <Image style={styles.filterImg} source={require('source/image/comm/down_small_gray.png')}></Image>
                    </View>
                </TouchableOpacity>

            </View>
        )
    }

    renderList() {
        return (
            <View style={{ backgroundColor: '#f9f9f9', flex: 1, marginTop: 10 }}>
                <FlatList
                    data={this.state.recordsList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <View key={index} style={[styles.itemContain, {borderTopLeftRadius: index == 0 ? 6:0, borderTopRightRadius: index == 0 ? 6:0, borderBottomLeftRadius: index == this.state.recordsList.length-1 ? 6:0, borderBottomRightRadius: index == this.state.recordsList.length-1 ? 6:0}]}>
                <View style={[styles.itemContain1, {borderBottomWidth: index < this.state.recordsList.length-1 ? 0.3:0}]}>
                    <View>
                        <Text style={styles.itemTitleText}>{item.value.orderBody}</Text>
                        <Text style={styles.itemDesText}>{item.value.createTime + ' ' + (item.value.userFullname ? item.value.userFullname : '')}</Text>
                    </View>

                    <View style={styles.desBox}>
                        <Text style={[styles.itemPriceText, { color: item.value.isIncome ? '#F99802' : '#222222' }]}>{item.value.isIncome ? ('+' + (item.value.totalAmountYuan).toFixed(2)) : item.value.totalAmountYuan ? '-' + (item.value.totalAmountYuan).toFixed(2) : ''}</Text>
                        <Text style={styles.itemDesText}>{item.value.payChannelName}</Text>
                    </View>
                </View>
            </View>
        )
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderFooter() {
        if (this.state.recordsList.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    renderFilterView() {
        if (this.state.showFilterType) {
            return (
                <View style={styles.filterViewBg}>
                    <ScrollView showsVerticalScrollIndicator={false} style={styles.filterTypeBg}>
                        {
                            this.state.showTypes.map((item,index) => {
                                return (
                                    <TouchableOpacity
                                        key={index}
                                        activeOpacity={0.8}
                                        style={styles.filterTypeBox}
                                        onPress={() => {
                                            this.setState({
                                                showFilterType: false,
                                                selectFilterType: item.code,
                                                selectFilterTypeTitle: item.desc == '全部' ? '全部类型' : item.desc
                                            }, function () {
                                                this.getWalletRecordsInfo(true);
                                            })
                                        }}
                                    >
                                        <Text style={this.state.selectFilterType == item.code ? styles.filterTypeSelText : styles.filterTypeText}>{item.desc}</Text>
                                        <View style={styles.sepLine} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </ScrollView>
                    <TouchableOpacity
                        activeOpacity={1.0}
                        style={{ flex: 1 }}
                        onPress={() => {
                            this.setState({
                                showFilterType: false
                            })
                        }}
                    />
                </View>


            )
        }
    }

    refreshData = () => {
        this.getWalletRecordsInfo(true);
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getWalletRecordsInfo(false);
    }

    getWalletRecordsInfo(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            merchantId: Constant.userInfo.merchantId,
            orderDate: this.state.consumeDate,
            tradeType: this.state.selectFilterType,
            accountType:1,
            // payChannels:[1,2,3,4,5,9,10]
        }
        HttpUtils.postRequest(HttpUrls.getTradePayLogList, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ recordsList: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                   
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            recordsList: this.state.recordsList.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

    getTradeTypeList() {
        let param = {
            type: 'TradeType'
        }
        HttpUtils.getRequest(HttpUrls.getTradeTypeList, param)
            .then((result) => {
                console.log(result.data)
                this.setState({
                    
                    showTypes: this.state.showTypes.concat(result.data)
                })
            })
            .catch((error) => {

            });
    }

}

const styles = StyleSheet.create({
    container: {
        width: screenW,
        flex: 1,
        backgroundColor: '#F9F9F9'
    },
    filterContain: {
        flexDirection: 'row',
        height: 45,
        backgroundColor: '#fff'
    },
    filterItemContain: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1
    },
    filterImg: {
        width: 20,
        height: 20,
        resizeMode: 'contain',
    },
    filterText: {
        fontSize: 14,
        color: '#696969'
    },
    itemContain: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginLeft: 10,
        marginRight: 10,
        paddingHorizontal: 16,
        backgroundColor: '#fff',
    },
    itemContain1: {
        height: 80,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        borderBottomColor: '#e6e6e6',
        borderBottomWidth: 0.5
    },
    itemTitleText: {
        fontSize: 15,
        color: '#222222',
    },
    desBox: {
        flexDirection: 'column',
        alignItems: 'flex-end'
    },
    itemPriceText: {
        fontSize: 18,
        color: '#222222',
        fontWeight: '600'
    },
    itemDesText: {
        color: '#999999',
        fontSize: 12,
        marginTop: 9
    },

    filterViewBg: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: 'rgba(0,0,0,0.5)'
    },
    filterTypeBg: {
        backgroundColor: '#fff',
        maxHeight: 320
    },
    filterTypeBox: {
        width: '100%',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center'
    },
    filterTypeText: {
        color: '#999999',
        fontSize: 14,
    },
    filterTypeSelText: {
        color: '#222222',
        fontSize: 16,
        fontWeight: '500'
    },
    sepLine: {
        position: 'absolute',
        bottom: 0,
        left: 20,
        right: 20,
        height: 0.5,
        backgroundColor: '#E4E4E4'
    },
    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },



})